<?php
/**
 * 这个是分享中心的小程序接口
 */
global $_GPC, $_W;
$uniacid = $this->_uniacid;

$uid = $_W['member']['uid'];
$openid = $_W['openid'];
$operation = 'display';
if(empty($uid)){
    $fans = mc_fansinfo($openid,0 ,$uniacid  );
    $uid = $fans['uid'];
}
if(isset($_GPC['op']) && !empty($_GPC['op'])){
    $operation = $_GPC['op'];
}
if($operation =='display'){
     $post_uid = $_GPC['uid'];
     $ret = pdo_fetch("select * from ".tablename("kbwdl_share_user"). " where uniacid='$uniacid' and openid='$openid' order by id desc ");
      
     $this->result(0, 'success', $ret);
}
/*获取我推广过的房源*/
elseif($operation =='myshare'){
    $limit = 4;
    if (isset($_GPC['limit']) && !empty($_GPC['limit'])) {
        $limit = intval($_GPC['limit']);
    }
    $page = max(1, $_GPC['page']);
    $pagesize = $limit;
    $startlimit = ($page - 1) * $pagesize;
    
    $sql_add_sec = " id in (select infoid from ".tablename("kbwdl_share_scence")." where uid='$uid' and uniacid='$uniacid' and category='sec' group by infoid  )";    
    
    $sql_add_newshop =  " id in (select infoid from ".tablename("kbwdl_share_scence")." where uid='$uid' and uniacid='$uniacid' and category='newshop' group by infoid  )";    
    
    $ret_sec = pdo_fetchall("select id, title, loyer,prix_unitaire, hall,room,garder, rent_type from " .tablename("kbwdl_house")." where $sql_add_sec  limit 50 " );
    
    $ret_newshop = pdo_fetchall("select newshouse_id, title, type,average_price  from " .tablename("kbwdl_house_info")." where $sql_add_newshop  limit 50");
    
    $data['salelist'] = array('sec'=>$ret_sec ,'newshop'=> $ret_newshop); 
    $data['total'] = $total;
    $this->result(0, 'success', $data);
    
}
/*获取我的客户*/
elseif($operation =='mytree'){
    $limit = 4;
    if (isset($_GPC['limit']) && !empty($_GPC['limit'])) {
        $limit = intval($_GPC['limit']);
    }
    $sql_add = " uniacid='$uniacid' and parent_openid='$openid' ";

    $page = max(1, $_GPC['page']);
    $pagesize = $limit;
    $startlimit = ($page - 1) * $pagesize;
    $category = array();
    if(isset($_GPC['total']) && ! empty($_GPC['total'])){
        $total = $_GPC['total'];  
     }else{
         $total = pdo_fetchcolumn("select count(*)  from ". tablename("kbwdl_share_user") ."  where $sql_add ");
    }       
    $ret = pdo_fetchall("select *  from " . tablename("kbwdl_share_user") . "   where $sql_add order by  addtime desc limit $startlimit,$pagesize ");
    if (!empty($ret)) {
        foreach ($ret as $key => $val) {               
            $ret[$key]['showtime'] = date('Y年m月d日', ($val['addtime']));              

        }
    }
    $data['salelist'] = $ret; 
    $data['total'] = $total;
    $this->result(0, 'success', $data); 
    
}
/**
 * 获取 我的佣金推广客户，登记过的
 */
elseif($operation == 'chargesUser'){
     $limit = 10;
    if (isset($_GPC['limit']) && !empty($_GPC['limit'])) {
        $limit = intval($_GPC['limit']);
    }
    $sql_add = " uniacid='$uniacid' and openid='$openid' and acttype='charges' ";
    /*查询 助理和经理的情况*/
    if(!isset($_GPC['queryMethod']) || empty($_GPC['queryMethod'])){
        /*么有这个参数，按当前用户的 类型查询，
         * = myself只查询 它自己的推荐人 用于我的推荐客户 
         * 否则 项目经理和项目助理
         */
        $broker = pdo_fetch("select id,openid,nickname,groupid,cgid from ".tablename("kbwdl_broker")." where openid='$openid'");
        if($broker['cgid']==1){
            //项目助理
            $bid = $broker['id'];
            $sql_add = " uniacid='$uniacid' and acttype='charges' and  houseid in (select newshouse_id from ".tablename('kbwdl_house_info')." where cgid1='$bid') ";
        }
         if($broker['cgid']==2){
            //项目经理
            $bid = $broker['id'];
            $sql_add = " uniacid='$uniacid' and acttype='charges' and  houseid in (select newshouse_id from ".tablename('kbwdl_house_info')." where cgid2='$bid') ";
        }
    }
    /*报备进度*/
    $step = intval($_GPC['step']);
    if($step){
        $sql_add.=" and hits='$step' ";
    }
    $keyword = trim($_GPC['keyword']);
    if($keyword){
        $sql_add.= " and  smalltext like '%$keyword%' ";
    }
    
    $page = max(1, $_GPC['page']);
    $pagesize = $limit;
    $startlimit = ($page - 1) * $pagesize;
    $category = array();
    $daofang = intval($_GPC['daofang']);
    if(isset($_GPC['total']) && ! empty($_GPC['total'])){
        $total = $_GPC['total'];  
     }else{
         $total = pdo_fetchcolumn("select count(*)  from ". tablename("kbwdl_favorite") ."  where $sql_add ");
         $daofang = pdo_fetchcolumn("select count(*)  from ". tablename("kbwdl_favorite") ."  where $sql_add and hits>1");
    }       
    $allsql = "select *  from " . tablename("kbwdl_favorite") . "   where $sql_add order by  addtime desc limit $startlimit,$pagesize ";
    $ret = pdo_fetchall( $allsql );
    $dot = $ids = "";
    
    if (!empty($ret)) {
        foreach ($ret as $key => $val) {               
            $ret[$key]['showtime'] = date('Y年m月d日', ($val['addtime'])); 
            $ret[$key]['addtime'] = date('Y-m-d H:i:s', ($val['addtime'])); 
            $ret[$key]['truename'] = '--';
            $ret[$key]['mobile'] = $ret[$key]['hide_mobile'] = '--';
            $sec = $this->_forms['charges_step'];
            if($val['hits']){
                $ret[$key]['step'] = $sec[$val['hits']];
            }else{
                $ret[$key]['hits'] = 1;
                $ret[$key]['step'] = $sec[1];
            }
            if(!empty($val['jsondata'])){
                $jsd = json_decode($val['jsondata'], true);
                $ret[$key]['truename'] = $jsd['truename'] ;
                $ret[$key]['mobile'] =  $jsd['mobile'] ;
                if($jsd['mobile']){
                    $ret[$key]['hide_mobile'] = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2',$jsd['mobile']);
                }
                $ret[$key]['jsondata'] = '';
            }           
            $ids .= $dot. $val['id'];
            $dot = ",";
        }
    }
    $logsarr = array();
    $ids = trim($ids, $dot);
    if($ids){
        $sql = "select id, addtime,num,infoid,note from ".tablename("kbwdl_actlog")." where infoid in($ids) and actname='chargestep' order by addtime asc";
        $logs = pdo_fetchall($sql);
        /*获取报备的记录*/
        if($logs){
            foreach($logs as $log){
                $log['num'] = $log['num'] ? $log['num'] :1;
                $logsarr[$log['infoid']][$log['num']] = $log;
            }
        }
    }
    $data['logs']  = $logsarr;
    $data['salelist'] = $ret; 
    $data['total'] = $total;
    $data['daofang'] = $daofang;
    /*获取总佣金额*/
    if(isset($_GPC['money']) && ! empty($_GPC['money'])){
        $data['money'] = $_GPC['money'];
    }else{
        $totalmoney = pdo_fetchcolumn("select SUM(money) from ".tablename("kbwdl_actlog")." where mark='$openid' and actname='yongjin' and  acttype=50 and uniacid='$uniacid' and isadd=1 ");
        $hasagentmoney = pdo_fetchcolumn("select SUM(money) from ".tablename("kbwdl_actlog")." where mark='$openid' and actname='agentMoney' and  acttype=51 and uniacid='$uniacid' and isadd=0 ");
        $data['money'] = max(0, (intval($totalmoney) - intval($hasagentmoney)));
        /*$hasagentmoney 统计进入 申请提现的佣金 num=1 表示待处理 0 表示已经成功提现*/
    }
    
   // $sql_add = "select SUM(money) from ".tablename("kbwdl_actlog")." where ecuid='$uid' and actname='yongjin' and  acttype=51 and uniacid='$uniacid' and isadd=0 ";
    $data['steplength'] = count($sec)>4?4: count($sec); /*前端的步骤swiper 翻页个数*/
    $this->result(0, 'success'.$sql_add, $data);    
}
/*保存我的分销人资料*/
elseif($operation=='modify'){
      $post_uid = $_GPC['uid'];
      /**/
      $save['uid'] = $_GPC['uid'];
      $save['name'] = $_GPC['username'];
      $save['mobile'] = $_GPC['mobile'];
      $save['identify'] = $_GPC['identify'];
      $save['openid'] = $openid;
      $save['uniacid'] = $uniacid;
      /*判断是否扫码进来的*/
      $scence = $_GPC['scence'];
      if(isset($_GPC['scence']) && !empty($_GPC['scence'])){
          $qrinfo = pdo_fetch("select * from ". tablename("kbwdl_share_scence")."  where scence='$scence' order by id desc");
          if($qrinfo['openid'] != $openid){
                $save['parent_openid'] = $qrinfo['openid'];
          }else{
              $save['parent_openid'] = '';
          }
      }
     /**/
      $ret = pdo_fetch("select * from ".tablename("kbwdl_share_user"). " where uniacid='$uniacid' and uid='$post_uid'");
      if($ret['id']>0){
          pdo_update("kbwdl_share_user", $save, array('id'=> $ret['id']));
      }else{
          $save['addtime'] = TIMESTAMP;
          pdo_insert("kbwdl_share_user", $save);
      }
      
       $this->result(0, 'success', $save);
}/*获取场景信息*/
elseif($operation=='scence'){
 
      /*判断是否扫码进来的*/
      $scence = $_GPC['scence'];
      $qrinfo = array();
      if(isset($_GPC['scence']) && !empty($_GPC['scence'])){
          $qrinfo = pdo_fetch("select * from ". tablename("kbwdl_share_scence")."  where scence='$scence' order by id desc");
          
      } 
    /*推广海报*/
    $ret = pdo_fetch("select * from ".  tablename("kbwdl_config")." where uniacid='$uniacid' and placeid=31 and module='kbwdl_shequzufang'");
    $qrinfo['viewtype'] = 0;
    $qrinfo['brokershare'] =0;
    if(!empty($ret['conf_value'])){
        $share = iunserializer($ret['conf_value']);
        $qrinfo['viewtype'] = (isset($share['viewtype'])&&  $share['viewtype']==1) ? 1: 0; 
        $qrinfo['brokershare'] = (isset($share['brokershare'])&&  $share['brokershare']==1) ? 1: 0; 
    }
    /*获取对应的转发经纪人信息*/
    $qrinfo['brokerid'] = 0;
    if(!empty($qrinfo['openid']) && ($qrinfo['brokershare']==1) ){
        /*brokershare=1 开启 经纪人转发后 替换房源的broker信息
         * 通过给 /kbwdl_shequzufang/pages/house/index?id=houseid&brokerid=
         * 再打开房源详情页面是 判断brokerid值存在就替换
         */
        $bopenid = $qrinfo['openid'];
        $b = pdo_fetchcolumn("select id from ". tablename("kbwdl_broker")." where groupid>0 and disabled=0 and ischecked=1 and  uniacid='$uniacid' and openid='$bopenid'");
        if($b){
            $qrinfo['brokerid'] = $b;
        }
         
    }
      
      $this->result(0, 'success', $qrinfo);
}
/**
 * 获取 海报信息
 */
elseif($operation =='make'){
    $infoid= $_GPC['infoid'];
    $category = $_GPC['category'];   
    $money = 0;
    $share_openid = $openid;
    
    if($category=='newshop'){
         $info = pdo_fetch("select * from ".tablename("kbwdl_house_info")." where uniacid='$uniacid' and id='$infoid'");
         
         $thumb = tomedia($info['logo']);
         $title = $info['title']? $info['title']: '楼盘';          
         $price = "主力户型：". $info['mark'].' '.$info['average_price']."  元/平米";       
         $housetype =   '楼盘优惠：'. $info['poster'] ;
         $mianji = '';
         
    }elseif($category =='sec'){
        $info = pdo_fetch("select * from ".tablename("kbwdl_house")." where uniacid='$uniacid' and id='$infoid'");
         $thumb = tomedia($info['thumb']);
         $title =  $info['title']? $info['title']: '房源'; 
         $info['loyer']  = $info['loyer'] ? $info['loyer'] : '面议';
         if($info['rent_type']==2){
              $price = '租金:'.$info['loyer']." 元/月";
         }else{
              $price = '售价:'.$info['loyer']." 万元";
         }
          if($val['rent_type']==0 && ($val['zhutype']==3)){
               $price = '转让:'.$info['loyer']." 元";
          }
        
        
         $housetype = '面积：'. $info['superficie']."㎡";
         if($info['room'] && $info['hall']){
              $housetype.= " 户型：". $info['room'].'房'. $info['hall'].'厅'. $info['garder'].'卫 ';
         }
         $mianji = '手机号：'. $user['mobile']  ;
         /*这个是*/
    }elseif($category =='paper'){
        $user = pdo_fetch("select * from ". tablename("kbwdl_share_user")." where uniacid='$uniacid' and uid='$uid' order by id desc");
        /*推广海报*/
        $ret = pdo_fetch("select * from ".  tablename("kbwdl_config")." where uniacid='$uniacid' and placeid=31 and module='kbwdl_shequzufang'");
        if(!empty($ret['conf_value'])){
            $share = iunserializer($ret['conf_value']);
            $thumb = tomedia($share['paper']); 
        }
        $info = pdo_fetch("select nickname, mobile from ".tablename("kbwdl_broker")." where groupid>0 and uniacid='$uniacid' and openid='$openid'");
        if(!empty($info)){
            $user['name'] = $info['nickname'] ? $info['nickname']: $user['name'];
            $user['mobile'] = $info['mobile'] ? $info['mobile']: $user['mobile'];
        }
        
        $title = '我是推广达人： '.$user['name'];
        $price = '购房有优惠';
        $housetype = '请扫描关注，或电话联系我！' ;
        $mianji = '手机号：'. $user['mobile']  ;
        
    }elseif($category == 'news'){
        
        $user = pdo_fetch("select * from ". tablename("kbwdl_share_user")." where uniacid='$uniacid' and uid='$uid' order by id desc");
        /*推广海报*/
        $info = pdo_fetch("select * from ".tablename("kbwdl_house_saleinfo")." where uniacid='$uniacid' and id='$infoid'");
         
        $thumb = tomedia($info['thumb']);
        $title =   $info['title'] ;
        $price = '购房有优惠';
        $housetype = '请扫描关注，或电话联系我！';        
        $mianji = '手机号：'. $user['mobile'];  
    }elseif($category =='broker'){
        $info = pdo_fetch("select * from ".tablename("kbwdl_broker")." where uniacid='$uniacid' and id='$infoid'");
        $info['thumb'] = empty($info['avatar'])? '/kbwdl_shequzufang/static/images/get_avatar.png': tomedia($info['avatar']);
        $thumb = $info['thumb'] ;
        /*如果是自己用海报图片*/
        if($info['openid'] == $openid){
            /*推广海报*/
            $ret = pdo_fetch("select * from ".  tablename("kbwdl_config")." where uniacid='$uniacid' and placeid=31 and module='kbwdl_shequzufang'");
            if(!empty($ret['conf_value'])){
                $share = iunserializer($ret['conf_value']);
                $thumb = tomedia($share['paper']); 
            }  
        }
       
        $title =  '我是'. $info['nickname'] ;
        $price = '购房有优惠';
        $housetype = '请扫描关注，或电话联系我！';        
        $mianji = '手机号：'. $info['mobile']; 
        /*增加推广店铺海报*/
    }elseif($category == 'myshop'){
        $info = pdo_fetch("select * from ".tablename("kbwdl_broker")." where uniacid='$uniacid' and id='$infoid'");
        $newshouse_ids = trim($info['newhouse'], ",");
        $share_openid = $info['openid']; /*其他用户转发我的店铺也是用我的openid*/
        /*获取新房的海报*/
         $newhouse = pdo_fetch("select * from ".tablename("kbwdl_house_info")." where uniacid='$uniacid' and newshouse_id in ({$newshouse_ids})");
         if(!empty($newhouse)){
             /*推广我的主营楼盘 */
             $thumb = tomedia($newhouse['logo']);
         }else{
              /*推广海报*/
            $ret = pdo_fetch("select * from ".  tablename("kbwdl_config")." where uniacid='$uniacid' and placeid=31 and module='kbwdl_shequzufang'");
            if(!empty($ret['conf_value'])){
                $share = iunserializer($ret['conf_value']);
                $thumb = tomedia($share['paper']); 
            } 
         }
         
        $title =  '我是'. $info['nickname'] ;
        $price = $newhouse['title'].' 购房有优惠';
        $housetype = '请扫描关注，或电话联系我！';        
        $mianji = '手机号：'. $info['mobile']; 
    }else{}
    $scence = $category.$uniacid. $infoid. $uid;
    //处理字数
    $title = cutstr($title,18);
    $price = cutstr($price,24);
    $housetype = cutstr($housetype,24);
    $mianji = cutstr($mianji,24);
    
    $hasmake = pdo_fetch("select * from ".  tablename("kbwdl_share_scence"). " where openid='$share_openid' and scence='$scence'");
    $shareData = array('uid'=>$uid,'openid'=>$share_openid,'scence'=>$scence, 'category'=>$category,'infoid'=>$infoid, 'money'=>$money, 'uniacid'=>$uniacid );
    
    if(empty($hasmake) ){
         pdo_insert("kbwdl_share_scence", $shareData);
    }else{
        pdo_update("kbwdl_share_scence",$shareData, array('id'=> $hasmake['id']));
    }
    if(empty($user)){
        $user = pdo_fetch("select * from ". tablename("kbwdl_share_user")." where uniacid='$uniacid' and uid='$uid' order by id desc");
    }
    $b = pdo_fetch ("select nickname,mobile,avatar from ".tablename("kbwdl_broker")." where uniacid='$uniacid' and openid='$openid'");
    if(!empty($b)){
        $this->module['config']['logo'] = $b['avatar'];
        if(empty($user['name'])){
            $user['name'] = $b['nickname'];
        }
        if(empty($user['mobile'])){
            $user['mobile'] = $b['mobile'];
        }
    }
    $ret = array(  'title'=> $title,
        'thumb'=> str_replace("http://", "https://", $thumb), 
        'openid'=> $openid,
        'broker'=> $b,
        'price'=> $price, 'housetype'=>$housetype,
        'mianji'=>$mianji  , 'ercode'=>$ercode  ,
        'avatar'=> str_replace("http://", "https://", tomedia($fans['avatar'])),
        'sitelogo'=>  str_replace("http://", "https://",tomedia($this->module['config']['logo'])),
        'timer'=> date('Y年m月d日'),
        'name'=>  $user['name'] ? $user['name'] : $this->module['config']['shopname'],
        'mobile'=> $user['mobile'] ? $user['mobile'] : $this->module['config']['phone']
            );
  
    load()->func('communication');     
    /*获取公众号access_token*/      
    load()->classs('wxapp.account');
    $account = pdo_fetch('select * from '.  tablename('account_wxapp'). " where acid= '".$uniacid ."'" );       
    $accObj = new WxappAccount( $account);        
    $ACCESS_TOKEN = $accObj->getAccessToken( );   
   // $ret['access_token'] = $ACCESS_TOKEN;
    //$ret['scence'] = $scence;
 
   
    /**
     * 二维码,通过公众号网页版获取
     */ 
    $ret['ercode'] =   $qrsrc = $_W['siteroot']."app/" .$this->createMobileUrl('share', array('op'=>'bqscence','weid'=>$uniacid,'category'=> $category, 'infoid'=> $id,'uid'=>$uid, 'scence'=>$scence));
   
     
    $this->result(0, 'success', $ret);
   
} 
?>
